// version 1.0 - By Kant@SeekRoad 2017-02-13

//var mod_url='/module';
var gridTabName = "管理列表";
var gridIconCls = "icon icon-edit";
var gridEditCount = 0;		//备用
var gridLastIndex = 0;		//备用
var gridIndexUrl = "";		//备用
var gridJsonUrl = "/listjson";
var gridSaveRowUrl = "/save";
var gridDeleteRowUrl = "/delete";
var gridUpdateUrl = "/update";
var gridConfirmUrl = "/confirm";	//备用
//弹窗相关参数
var gridEditUrl = "/dialog";
var dialogWidth = 500;
var dialogHeight = 500;
var dialogModal = true;

//$(function(){gridInit();});
function gridInit(){
 var args=arguments[0], typeToolBar='search';
 if(!$.isEmptyObject(args)){
    if(args.hasOwnProperty('toolbar')){typeToolBar=args['toolbar'];}
 }
 $('#gridlist').datagrid(
  jQuery.extend(
   getGridExtendParam(),
   {
	fit:true,
	striped:true,		//交替显示行背景
	rownumbers:true,	//行号
	toolbar:getGridToolbarField(typeToolBar),
	columns:getGridColumnsField(),
	onBeforeEdit:function(index,row){
		row.editing = true;
		$('#gridlist').datagrid('refreshRow', index);
		gridEditCount++;
	},
	onAfterEdit:function(index,row){
		row.editing = false;
		$('#gridlist').datagrid('refreshRow', index);
		gridEditCount--;
	},
	onCancelEdit:function(index,row){
		row.editing = false;
		$('#gridlist').datagrid('refreshRow', index);
		gridEditCount--;
	}
	/*//只允许一行在编辑状态时有用
	onClickRow:function(rowIndex){
		if (gridLastIndex != rowIndex){
			$('#gridlist').datagrid('endEdit', gridLastIndex);
			$('#gridlist').datagrid('beginEdit', rowIndex);
		}
		gridLastIndex = rowIndex;
	}//*/
   }
  ));
}

function gridDeleteRow(index){
	$.messager.confirm('确认','是否真的删除?',function(r){if (r){
	    var row = $('#gridlist').datagrid('getRows')[index];
		if (row.state=='create') {
			$('#gridlist').datagrid('deleteRow', index);
			gridRefreshRow(index,$('#gridlist').datagrid('getRows').length);
		}else{
			$.ajax({
				url: mod_url+gridDeleteRowUrl,
				cache: false, dataType: "json", type: "post",
				data: getGridDelRowData(row),	//{id:row.id, state:row.state},	// name:row.name, type:row.type, order:row.order, 
				success: function(jsonObj){
					if (jsonObj.state=="success") {
						$('#gridlist').datagrid('deleteRow', index);
						gridRefreshRow(index,$('#gridlist').datagrid('getRows').length);
					}else{
						$.messager.alert("提示", jsonObj.msg, "error"); 
					}
				},
				error: function(jsonObj){
					$.messager.alert("提示", "服务器忙，请稍后再提交删除！", "error"); 
				}
			});
		}
	} });
}
function gridSaveRow(index){
	/*////==============================
	//说明： 2013-4-28 by Kant
	//		暂时没有找到直接读取编辑中的值
	//		所以采用先保存然后读取行数据的办法
	//		以后如果找到方法了可以直接修改
	//*///==============================
	//保存原始内容值
	var rowOld = $('#gridlist').datagrid('getRows')[index];
	var rowvalold = getGridRowData(rowOld);
	$('#gridlist').datagrid('endEdit', index);	//保存新记录
	var row = $('#gridlist').datagrid('getRows')[index];	//读取修改后的内容值
	if(gridSaveRowBefore(row,rowOld)){
	$.ajax({
		url: mod_url+gridSaveRowUrl,
		cache: false, dataType: "json", type: "post",
		data: getGridRowData(row),
		success: function(jsonObj){
			if (jsonObj.state=="success") {
				$('#gridlist').datagrid('updateRow',{index:index, row:setGridRowData(jsonObj.row)} );	//插入记录存入新id，修正状态值
			}else{
				//保存失败，还原原始内容值
				$('#gridlist').datagrid('updateRow',{index:index, row:rowvalold});
				$('#gridlist').datagrid('beginEdit', index);
				$.messager.alert("提示", jsonObj.msg, "error"); 
			}
		},
		error: function(jsonObj){
			//保存失败，还原原始内容值
			$('#gridlist').datagrid('updateRow',{index:index, row:rowvalold});
			$('#gridlist').datagrid('beginEdit', index);
			$.messager.alert("提示", "服务器忙，请稍后再提交保存！", "error");
		}
	});
	}else{
		$('#gridlist').datagrid('updateRow',{index:index, row:rowvalold});
		$('#gridlist').datagrid('beginEdit', index);
	}
}
function gridEditRow(index){
	$('#gridlist').datagrid('beginEdit', index);
}
function gridCancelRow(index){
	$('#gridlist').datagrid('cancelEdit', index);
}
function gridAddRow(){
	//-- 2015-3-5 Kant 取消同时只能增加一条记录的限制
	//if (gridEditCount > 0){
	//	$.messager.alert('警告','当前还有'+gridEditCount+'记录正在编辑，不能增加记录。');
	//	return;
	//}
	//-- 2015-3-5 ----------
	//$('#gridlist').datagrid('endEdit', gridLastIndex);		//取消正在编辑的行
	var row = $('#gridlist').datagrid('getRows');
	//gridLastIndex = row.length;
	//$('#gridlist').datagrid('appendRow', getGridNewRowData() );
	gridLastIndex = 0;
	$('#gridlist').datagrid('insertRow',{index:gridLastIndex, row:getGridNewRowData()} );	//在指定位置插入行
	gridRefreshRow(gridLastIndex,row.length);
	$('#gridlist').datagrid('selectRow', gridLastIndex );
	$('#gridlist').datagrid('beginEdit', gridLastIndex );
}
function gridRefreshRow(startRowNo,endRowNo){
	for (var i=startRowNo;i<endRowNo;i++){
		$('#gridlist').datagrid('refreshRow', i );
	}
}

//--- 以下为弹窗相关函数 ----------------------------------------------------------------
function griddialogInit(){
	if($('#griddialog').length<1){
		$('body').append("<div id=\"griddialog\" style=\"display:none;padding:5px;\"></div>");
	}
}
function gridEditDialog(act,rowid){
	var str_url,str_title,str_icon;
	if (act=="add"){
		str_url = mod_url+gridEditUrl;
		str_title = '增加记录';
		str_icon = 'icon-add';
	}else{
		str_url = mod_url+gridEditUrl+'-'+rowid;
		str_title = '编辑记录';
		str_icon = 'icon-edit';
	}
	griddialogInit();
	$('#griddialog').show();
	$('#griddialog').dialog({
		title:str_title,
		iconCls:str_icon,
        modal:dialogModal,
		resizable:true,
		href:str_url,
		width:dialogWidth,
		height:dialogHeight,
		onClose:function(){$(this).dialog('destroy');},
		buttons:getDialogSubmitBtn()
	});
}
function getDialogSubmitBtn(){
    var args=arguments[0], fn_CheckFrom,s_SaveUrl;
    fn_CheckFrom = griddialogCheckFrom;
    s_SaveUrl = mod_url+gridSaveRowUrl;
    if(!$.isEmptyObject(args)){
        if(args.hasOwnProperty('checkfrom') && typeof(args['checkfrom'])==="function"){ fn_CheckFrom = args['checkfrom']; }
        if(args.hasOwnProperty('url')){ s_SaveUrl = args['url']; }
    }
	return [{
		text: '提交&nbsp;', iconCls: 'icon-ok', id: 'btnSave',
		handler: function(){
		  var chkResult = fn_CheckFrom();
		  if (chkResult[0]==true){
			griddialogDisableFrom();
			$.ajax({
				url: s_SaveUrl,
				cache: false, dataType: "json", type: "post",
				data: griddialogJaonFromVal(),
				success: function(jsonObj){
					if (jsonObj.state=="success") {
						griddialogAjaxSuccess(jsonObj)
					}else{
						$.messager.alert("提示", jsonObj.msg, "error");
						griddialogEnableFrom();
					}
				},
				error: function(jsonObj){
					$.messager.alert("提示", "服务器忙，请稍后再提交保存！", "error");
					griddialogEnableFrom();
				}
			});
		  }else{
            if(chkResult[0]!='noalert'){
                if((chkResult[1]).length>0){
                    $.messager.alert("提示", chkResult[1], "error");
                }else{
                    $.messager.alert("提示", "表单检查没有通过，请填写完整后再提交！", "error");
                }
			}
		  }
		}
	}, {
		text: '取消&nbsp;', iconCls: 'icon-cancel', id: 'btnCancel',
		handler: function(){$('#griddialog').dialog('destroy');}
	}];
}
function griddialogCheckFrom(){
	var msg = "",state=true;
	/*
	if($("#ProductID")==null || $("#ProductID").combobox("getValue")==null || $("#ProductID").combobox("getValue")==""){ 
		msg="1";
		state=false;
	}
	if (!$('#Link').validatebox('isValid')){
		msg="2";
		state=false;
	} */
	return Array(state,msg);
}
function griddialogJaonFromVal(){
	return $('form[name=fadd]').serialize();
}
function griddialogDisableFrom(){
	$('#btnSave').linkbutton('disable');
}
function griddialogEnableFrom(){
	$('#btnSave').linkbutton('enable');
}
function griddialogAjaxSuccess(jsonObj){
	$('#griddialog').dialog('destroy');
	$('#gridlist').datagrid('reload');
	//location.href=mod_url+gridIndexUrl;
}

//--- 以下为各个表格自定义设置内容 ----------------------------------------------------------------
function getGridExtendParam(){		//返回个性化补充datagrid属性参数
	return {
	    title:gridTabName,
	    iconCls:gridIconCls,
		//singleSelect:true,	//只允许选择一行
		pagination:true,	//表格底部显示分页工具栏
		pageSize:30,		//初始化每页记录数
		url:mod_url+gridJsonUrl
		/*
		fitColumns:true,	//自适应列宽，设置这个可以不用每一列设置宽度
		width:720,
		height:400,
		frozenColumns:[[
			{field:'no',title:'编号',width:60,align:'center'}	/* 冻结列 * /
		]], */
	};
}
function getGridToolbarField(){		//返回搜索栏的按钮设置内容
    var args=arguments[0];
    if(args=='none'){
	   return undefined;
    }else if(args=='search'){
	   return "#tbsearch";
    }else{  // args=='row'
	   return [
		 {text:'增加',iconCls:'icon-add',handler:gridAddRow},
		 {text:'刷新',iconCls:'icon-reload',handler:function(){location.reload();} }
	   ];
    }
}
function getGridColumnsField(){		//格式化datagrid表格 返回Json格式
	//return undefined;     //返回默认值，可以在html页面的table上直接填写列格式
	return [[
		{field:'id',title:'字典ID',width:80,align:'center',sortable:true},
		{field:'name',title:'字典名称',width:200,align:'center',
			editor:{type:'validatebox',options:{required:true,missingMessage:"输入不能为空！", validtype:'minLength[5]'}}
		},
		{field:'text',title:'具体内容',width:250,align:'center',
			editor:{type:'validatebox',options:{required:true,missingMessage:"输入不能为空！", validtype:'minLength[5]'}}
		},
		{field:'value',title:'导入代码',width:80,align:'center',
			editor:{type:'validatebox',options:{required:true,missingMessage:"输入不能为空！", validtype:'minLength[5]'}}
		},
		{field:'type',title:'字典类型',width:80,align:'center',sortable:true,
			editor:{type:'validatebox',options:{required:true,missingMessage:"输入不能为空！", validtype:'minLength[5]'}}
			/*editor:{type:'combobox',options:{valueField:'id', textField:'text',panelHeight:63,data:json_select, required:true, missingMessage:"请选择字典类型..."} /*,multiple:"multiple"/*多选* /},
			formatter:function(value,row,index){
				for (var tt in json_select){ 
					if(json_select[tt].id==value)return json_select[tt].text;
				}
			}*/
		},
		{field:'order',title:'显示顺序',width:80,align:'center',sortable:true,editor:{type:'numberbox',options:{required:true,missingMessage:"仅接受数字输入！"}}},
		{field:'action',title:'操作',width:100,align:'center',
			formatter:function(value,row,index){
				if (row.editing){
					var s = '<a href="#" onclick="gridSaveRow('+index+')">保存</a> | ';
					var c = '<a href="#" onclick="gridCancelRow('+index+')">取消</a>';
					return s+c;
				} else {
					var e = '<a href="#" onclick="gridEditRow('+index+')">编辑</a> | ';
					var d = '<a href="#" onclick="gridDeleteRow('+index+')">删除</a>';
					return e+d;
				}
			}
		}
	]];
}
function gridSaveRowBefore(rowDate,oldrowData){		// 提交数据前检查数据合法性，有需要时重写本函数
	return true;
}
function getGridNewRowData(){		//格式化传递参数格式 返回Json格式
	return {id:'',name:'',text:'',value:'',type:'',order:1,state:'create'};
}
function getGridRowData(row){		//格式化传递参数格式 返回Json格式
	return {id:row.id, name:row.name, text:row.text, value:row.value, type:row.type,  order:row.order, state:row.state};
}
function setGridRowData(row){		//系统处理后返回参数格式化更新 返回Json格式
	return {id:row.id, state:''};	//默认没有更新内容
}
function getGridDelRowData(row){	//格式化删除行传递参数格式 返回Json格式
	return {id:row.id, state:row.state};	// name:row.name, type:row.type, order:row.order, 
}
function resetSeaPanel(){			//改变浏览器窗口大小时触发更新检索面板选项宽度，调用：$(window).resize(function(){setTimeout(resetSeaPanel,500);});
	var ddw=$('#tbsearch').width(),ddww=0;
	var ddfw=$('#tbsea_l').width(),ddfww=0;
	var ddrw=$('#tbsea_r').width();
	$("#tbsearch .tbseaItem").each(function(i){
		ddww+=$(this).width()+4;
		if(ddww+ddrw<=ddw){
			ddfww=ddww;
		}
	});
	if(ddww+ddrw<=ddw){
		if(ddww>ddfw){
			$('#tbsea_l').width(ddww);
		}
	}else{
		$('#tbsea_l').width(ddfww+10);	//ddrw
	}
}